<?php

namespace app\common\business;

use app\common\model\mysql\User as UserModel;
use app\common\lib\Str;
use app\common\lib\Time;

/**
 * Class User
 * @package app\common\business
 */
class User {
    public $userObj = null;

    public function __construct() {
        $this->userObj = new UserModel();
    }

    /**
     * 商城登录
     * @param $data
     * @return array|bool
     * @throws \think\Exception
     */
    public function login($data) {
        $redisCode = cache(config('redis.code_pre') . $data['phone_number']);
        if (empty($redisCode) || $redisCode != $data['code']) {
            throw new \think\Exception('不存在该验证码', -1009);
        }

        // 根据phone_number判断表是否该用户，不存在则新增
        $user = $this->userObj->getUserByPhoneNumber($data['phone_number']);
        if (!$user) {
            $user = [
                'username'     => '用户-' . $data['phone_number'],
                'phone' => $data['phone_number'],
                'type'         => $data['type'],
                'status'       => config('status.mysql.table_normal'),
            ];
            try {
                $this->userObj->save($user);
                $userId = $this->userObj->id;
            } catch (\Exception $e) {
                throw new \think\Exception('数据库内部异常');
            }
        } else {
            $userId = $user->id;
            $updateData = [
                'last_time' => time(),
                'last_ip' => request()->ip(),
            ];
            $this->userObj->updateById($user['id'], $updateData);
        }

        // 生成token
        $token = Str::getLoginToken($data['phone_number']);
        $redisData = [
            'id'       => $userId,
            'username' => $user['username'],
        ];
        // 缓存
        $res = cache(config('redis.token_pre') . $token, $redisData, Time::userLoginExpiresTime($data['type']));

        return $res ? ['uid' => $userId, 'token' => $token, 'username' => $user['username']] : false;
    }

    /**
     * 返回正常用户数据
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserById($id) {
        $user = $this->userObj->getUserById($id);
        if (!$user || $user->status != config('status.mysql.table_normal')) {
            return [];
        }
        return $user->toArray();
    }

    /**
     * 返回正常用户数据
     * @param $username
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserByUsername($username) {
        $user = $this->userObj->getUserByUsername($username);
        if (!$user || $user->status != config('status.mysql.table_normal')) {
            return [];
        }
        return $user->toArray();
    }

    /**
     * @param $id
     * @param $data
     * @return bool
     * @throws \think\Exception
     */
    public function update($id, $data) {
        $user = $this->getNormalUserById($id);
        if (!$user) {
            throw new \think\Exception('用户不存在');
        }

        // 检查用户名是否存在
        $userResult = $this->getNormalUserByUsername($data['username']);
        if ($userResult && $userResult['id'] != $id) {
            throw new \think\Exception('该用户名已经存在请重新设置');
        }
        return $this->userObj->updateById($id, $data);
    }
}